/* components */
import ChatAIMessageAvatar from '@src/component/business/BizChatPanel/chat/components/message-avatar'
import { SettingGPTViewFeedback } from '@src/modules/setting/gpt/components'
import Chart from '@src/modules/setting/gpt/components/chart'
// @ts-ignore
import VueMarkdown from 'vue-markdown'
/* enum */
import { ComponentNameEnum } from '@src/component/business/BizChatPanel/chat/model/enum'
/* hooks */
import { useCopy } from '@hooks/useElement'
/* model */
import { COPY_SUCCESS, COPY_ERROR } from '@src/model/const/Alert'
import { OpenAIMessageItemType } from '@src/component/business/BizChatPanel/chat/model'
/* scss */
import '@src/component/business/BizChatPanel/chat/components/message-item/index.scss'
/* vue */
import { defineComponent, PropType } from 'vue'
/* util */
import { getAssistantLoadingMessage, getSystemMessage, isNotUserMessage, isUserMessage } from '@src/component/business/BizChatPanel/chat/util'
import { getRootWindowInitData } from '@src/util/window'
import { isEmpty, isFalsy, isNotEmpty } from '@src/util/type'
import { openTabForWikiView, openTabForWikiList } from '@src/util/business/openTab'
import { setClipboardData } from '@src/util/dom'
import DOMPurify from 'dompurify'
import { marked } from 'marked';
import platform from '@src/platform'
/* types */
import { ChatBusinessSourceDocumentType } from '@src/component/business/BizChatPanel/chat/types'
import { message } from '@src/util/message'
import { GetRobotTextToReportResult } from '@src/modules/setting/gpt/types/chartT'

type ChartComponent = InstanceType<typeof Chart>

export type ChatAIMessageItemProps = {
  item: OpenAIMessageItemType;
  preItem: OpenAIMessageItemType;
  isFirst: boolean;
  isLast: boolean;
}

export interface ChatAIMessageItemSetupState {
  
}

export enum ChatAIMessageItemEventEnum {
  Input = 'input',
  Like = 'like',
  Dislike = 'dislike',
  Refresh = 'refresh',
}

export default defineComponent({
  name: ComponentNameEnum.ChatAIMessageItem,
  components: {
    [ChatAIMessageAvatar.name]: ChatAIMessageAvatar,
    VueMarkdown,
    Chart
  },
  emits: [
    ChatAIMessageItemEventEnum.Like,
    ChatAIMessageItemEventEnum.Dislike,
    ChatAIMessageItemEventEnum.Refresh,
  ],
  props: {
    item: {
      type: Object as PropType<OpenAIMessageItemType>,
      default: () => ({})
    },
    preItem: {
      type: Object as PropType<OpenAIMessageItemType>,
      default: () => ({})
    },
    isFirst: {
      type: Boolean as PropType<boolean>,
      default: false
    },
    isLast: {
      type: Boolean as PropType<boolean>,
      default: false
    },
    isStreaming: {
      type: Boolean,
      default: false
    },
  },
  setup(props: ChatAIMessageItemProps, { slots, emit }) {
    
  },
  data() {
    return {
      isShowFullScreen: false
    }
  },
  computed: {
    createTime(): any {
      return this.item.createTime || ''
    },
    chartComponent(): ChartComponent {
      return this.$refs.Chart as ChartComponent
    },
    chartTitle(): string {
      return this.preItem?.content || ''
    },
    echartData(): GetRobotTextToReportResult[] {
      return this.item.echartData || [] as GetRobotTextToReportResult[]
    },
    /** 
     * @description 是否是用户消息
    */
    isUserMessage(): boolean {
      return isUserMessage(this.item)
    },
    /** 
     * @description 是否不为用户消息
    */
    isNotUserMessage(): boolean {
      return isNotUserMessage(this.item)
    },
    isAIAnswerIng(): boolean {
      return this.item?.content == getAssistantLoadingMessage()?.content || this.isStreaming
    },
    isShowOperator(): boolean {
      return this.isNotUserMessage && isFalsy(this.isAIAnswerIng) && this.isNotFirst && isFalsy(this.isSystemMessage)
    },
    isBI(): boolean {
      return Boolean(this.item.isBI)
    },
    isShowOperatorButtons(): boolean {
      return this.isNotFirst && isFalsy(this.isStopMessage) && isEmpty(this.item.echartData) && isFalsy(this.isBI)
    },
    isSystemMessage(): boolean {
      return this.item?.content == getSystemMessage().content
    },
    /** 
     * @description 是否为左侧消息
     * 不是用户消息，即为左侧消息
    */
    isLeftMessage(): boolean {
      return this.isNotUserMessage
    },
    isShowRefresh(): boolean {
      return this.isNotFirst && this.isLast && this.isNotUserMessage
    },
    isNotFirst(): boolean {
      return isFalsy(this.isFirst)
    },
    isStopMessage(): boolean {
      return Boolean(this.item.isStop)
    },
    /** 
     * @description 是否为右侧消息
     * 是用户消息，即为右侧消息
    */
    isRightMessage() {
      return this.isUserMessage
    },
    likeStatus(): number | null | undefined {
      return this.item?.likeStatus
    },
    isLikeStatus(): boolean {
      return this.likeStatus == 1
    },
    isDisLikeStatus(): boolean {
      return this.likeStatus == 0
    },
    loginUser() {
      const rootWindowInitData = getRootWindowInitData()
      return {
        displayName: rootWindowInitData?.user?.displayName || ''
      }
    },
    itemClassNames() {
      return {
        [ComponentNameEnum.ChatAIMessageItem]: true,
        "chat-ai-message-list-item-left": this.isLeftMessage,
        "chat-ai-message-list-item-right": this.isRightMessage,
        "chat-ai-message-list-item-like-status": this.isLikeStatus,
        "chat-ai-message-list-item-dislike-status": this.isDisLikeStatus,
        "chat-ai-message-list-item-stop-status": this.isStopMessage,
      }
    },
    contentHTML(): string {
      try {
        return this.item.content || ''
        // return DOMPurify.sanitize(marked.parse(this.item.content))
      } catch (error) {
        return this.item.content || ''
      }
    },
    likeIconClassNames(): Record<string, boolean> {
      return {
        "iconfont": true,
        "icon-like-fill": this.isLikeStatus,
        "icon-dianzan": isFalsy(this.isLikeStatus),
        "chat-ai-message-list-item-operator-like-icon": true
      }
    },
    dislikeIconClassNames(): Record<string, boolean> {
      return {
        "iconfont": true,
        "icon-cai_fill": this.isDisLikeStatus,
        "icon-cai": isFalsy(this.isDisLikeStatus),
        "chat-ai-message-list-item-operator-dislike-icon": true
      }
    }
  },
  watch: {
    echartData: {
      handler(newValue) {
        
        if (isEmpty(newValue)) {
          return
        }
        
        this.$nextTick(() => {
          this.isShowFullScreen = this.chartComponent?.isShowChart
        })
        
      },
      immediate: true
    }
  },
  methods: {
    /** 
     * @description 复制消息
    */
    copyHandler() {
      setClipboardData(
        this.item.content,
        () => {
          message.info("已复制到粘贴板，快去粘贴吧")
        }
      )
    },
    /** 
     * @description 提交点赞事件
    */
    emitLikeHandler() {
      this.$emit(ChatAIMessageItemEventEnum.Like, this.item)
    },
    /** 
     * @description 提交点踩事件
    */
    emitDislikeHandler() {
      this.$emit(ChatAIMessageItemEventEnum.Dislike, this.item)
    },
    /** 
     * @description 提交重新回答事件
    */
    emitRefreshHandler() {
      this.$emit(ChatAIMessageItemEventEnum.Refresh, this.item)
    },
    /** 
     * @description 点赞
    */
    likeHandler() {
      this.emitLikeHandler()
    },
    /** 
     * @description 点踩
    */
    dislikeHandler() {
      this.emitDislikeHandler()
    },
    /** 
     * @description 重新回答
    */
    refreshHandler() {
      
      if (isFalsy(this.isShowRefresh)) {
        return
      }
      
      this.emitRefreshHandler()
      
    },
    /** 
     * @description 获取消息名称
    */
    getName() {
      
      // 如果是用户消息，则显示用户名称
      if (this.isUserMessage) {
        return this.loginUser?.displayName
      }
      
      // 如果不是用户消息，则显示 小宝AI
      return '小宝AI'
      
    },
    onTipClickHandler() {
      openTabForWikiList()
    },
    onFullScreenHandler() {
      this.chartComponent?.onFullScreenHandler()
    },
    renderBusinessSourceDocuments() {
      
      if (this.isUserMessage) {
        return
      }
      
      if (isEmpty(this.item?.businessSourceDocuments)) {
        return
      }
      
      const businessSourceDocuments = this.item?.businessSourceDocuments || []
      
      const isHttps = businessSourceDocuments?.every((item: ChatBusinessSourceDocumentType) => {
        return item?.url?.startsWith('https')
      })
      
      const text = isHttps ? '参考链接：' : '参考文章：'
      
      return (
        <div class="chat-ai-message-list-item-message-session-business-source-documents-block">
          
          <span class="chat-ai-message-list-item-message-session-business-source-documents-title">
            { text }
          </span>
          
          {businessSourceDocuments.map((item: ChatBusinessSourceDocumentType) => {
            return this.renderBusinessSourceDocumentTag(item)
          })}
          
        </div>
      )
    },
    renderBusinessSourceDocumentTag(item: ChatBusinessSourceDocumentType) {
      
      const id = item?.id || ''
      const name = item?.name || ''
      const url = item?.url || ''
      
      const isHttpsUrl = url?.startsWith('https')
      
      const onClickHandler = () => {
        
        if (isHttpsUrl) {
          platform.openLink(url)
          return
        }
        
        if (isFalsy(id)) {
          return
        }
        
        openTabForWikiView(id)
        
      }
      
      return (
        <el-tag onClick={onClickHandler}>
          { name }
        </el-tag>
      )
    },
    renderTipContent() {
      
      if (this.isAIAnswerIng) {
        return
      }
      
      if (this.isFirst && this.isNotUserMessage) {
        return
      }
      
      if (this.isUserMessage) {
        return
      }
      
      if (isEmpty(this.item?.businessSourceDocuments)) {
        return
      }
      
      const content = '更多内容前往知识库查询 >>'
      
      return (
        <div 
          class="chat-ai-message-list-item-message-session-tip-block"
          onClick={this.onTipClickHandler}
        >
          { content }
        </div>
      )
      
    }
  },
  render() {
    return (
      <div class={this.itemClassNames}>
        
        <div class="chat-ai-message-list-item-bottom">
          
          <div class="chat-ai-message-list-item-name">
            
            <span class="chat-ai-message-list-item-text">
              { this.getName() }
            </span>
            
          </div>
          
          <div class="chat-ai-message-list-item-message-session">
            <div class="chat-ai-message-list-item-message-block"> 
              
              <div class="chat-ai-message-list-item-message-content">
                {
                  this.contentHTML ?
                  (
                    <div
                      class="chat-ai-message-list-item-message-content-html"
                      // @ts-ignore
                      domPropsInnerHTML={this.contentHTML}
                    >
                  </div> 
                  )
                : (
                  <Chart 
                    ref="Chart"
                    title={this.chartTitle}
                    eData={this.echartData}
                  />
                )
                }
              </div>
              
              { this.renderBusinessSourceDocuments() }
              
            </div>
          </div>
          
          <div class="chat-ai-message-list-item-operator" v-show={this.isShowOperator}>
            
            <div class="chat-ai-message-list-item-operator-left">
              
              <div 
                class="chat-ai-message-list-item-operator-item"
                v-show={this.isShowRefresh} 
                onClick={this.refreshHandler}
              >
                <i class="iconfont icon-updete"></i>
                <span>
                  换个回答
                </span>
              </div>
              
              <div 
                class="chat-ai-message-list-item-operator-item"
                v-show={this.isShowFullScreen} 
                onClick={this.onFullScreenHandler}
              >
                <i class="iconfont icon-quanping1"></i>
                <span>
                  全屏查看
                </span>
              </div>
              
            </div>
            
            <div 
              class="chat-ai-message-list-item-operator-other"
              v-show={this.isShowOperatorButtons}
            >
              {/* start 复制 */}
              <i 
                class="iconfont icon-file-copy chat-ai-message-list-item-operator-copy-icon"
                onClick={this.copyHandler}
              >
              </i>
              {/* end 复制 */}
              
              {/* start 点赞 */}
              <i 
                class={this.likeIconClassNames}
                onClick={this.likeHandler}
              >
              </i>
              {/* end 点赞 */}
              
              {/* start 点踩 */}
              
              <i 
                class={this.dislikeIconClassNames}
                onClick={this.dislikeHandler}
              >
              </i>
              
            </div>
            
          </div>
          
        </div>
        
      </div>
    ) as any
  }
})
